package org.Lin.dao;

import org.Lin.model.OperationLog;
import org.Lin.util.DatabaseUtil;

import java.sql.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

public class OperationLogDAO {

    public void insert(OperationLog log) throws SQLException {
        String sql = "INSERT INTO OperationLog(operation_object, operation_code, operation_content) VALUES (?, ?, ?)";
        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setString(1, log.getOperationObject());
            stmt.setString(2, log.getOperationCode());
            stmt.setString(3, log.getOperationContent());
            stmt.executeUpdate();
        }
    }

    public List<OperationLog> findAll() throws SQLException {
        List<OperationLog> logs = new ArrayList<>();
        String sql = "SELECT * FROM OperationLog";
        try (Connection conn = DatabaseUtil.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {
            while (rs.next()) {
                logs.add(mapToLog(rs));
            }
        }
        return logs;
    }

    private OperationLog mapToLog(ResultSet rs) throws SQLException {
        OperationLog log = new OperationLog();
        log.setID(rs.getInt("ID"));
        log.setOperationObject(rs.getString("operation_object"));
        log.setOperationCode(rs.getString("operation_code"));
        log.setOperationContent(rs.getString("operation_content"));
        log.setOperationTime(rs.getObject("operation_time", LocalDateTime.class));
        return log;
    }
}
